<template>
  <div class="admin-logs">
    <div class="tab-content">
      <!-- 筛选栏 -->
      <el-card class="filter-card">
        <el-form :inline="true" :model="logFilterForm" class="filter-form">
          <el-form-item label="管理员ID">
            <el-input v-model="logFilterForm.adminId" placeholder="请输入管理员ID" />
          </el-form-item>
          <el-form-item label="操作人">
            <el-input v-model="logFilterForm.operator" placeholder="请输入操作人" />
          </el-form-item>
          <el-form-item label="操作模块">
            <el-select v-model="logFilterForm.module" placeholder="请选择操作模块" style="width: 200px;">
              <el-option label="全部" value="" />
              <el-option label="留学生审核" value="留学生审核" />
              <el-option label="企业认证审核" value="企业认证审核" />
              <el-option label="需求审核" value="需求审核" />
              <el-option label="请求管理" value="请求管理" />
              <el-option label="管理员管理" value="管理员管理" />
              <el-option label="角色管理" value="角色管理" />
            </el-select>
          </el-form-item>
          <el-form-item label="操作结果">
            <el-select v-model="logFilterForm.actionResult" placeholder="请选择操作结果" style="width: 150px;">
              <el-option label="全部" value="" />
              <el-option label="成功" value="success" />
              <el-option label="失败" value="failed" />
              <el-option label="错误" value="error" />
            </el-select>
          </el-form-item>
          <el-form-item label="操作时间">
            <el-date-picker
              v-model="logFilterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogFilter">筛选</el-button>
            <el-button @click="handleLogReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 操作记录列表 -->
      <el-card class="table-card">
        <el-table :data="logData" style="width: 100%" v-loading="loading">
          <el-table-column prop="operator" label="操作人" min-width="12%" />
          <el-table-column prop="operationTime" label="操作时间" min-width="15%" />
          <el-table-column prop="module" label="操作模块" min-width="12%">
            <template #default="scope">
              <el-tag :type="getModuleType(scope.row.module)">
                {{ getModuleText(scope.row.module) }}
              </el-tag>
            </template>
          </el-table-column>
                  <el-table-column prop="operationType" label="操作详情" min-width="20%">
          <template #default="scope">
            <span>{{ scope.row.operationType }}</span>
          </template>
        </el-table-column>
          <el-table-column prop="ipAddress" label="IP地址" min-width="12%" />
          <el-table-column prop="description" label="操作内容" min-width="30%" />
          <el-table-column label="操作" min-width="12%">
            <template #default="scope">
              <el-button type="info" size="small" @click="handleViewLogDetail(scope.row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="logDetailDialogVisible"
      title="操作详情"
      width="60%"
    >
      <div v-if="currentLogDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="操作人">{{ currentLogDetail.operator }}</el-descriptions-item>
          <el-descriptions-item label="操作时间">{{ currentLogDetail.operationTime }}</el-descriptions-item>
          <el-descriptions-item label="操作模块">{{ currentLogDetail.module }}</el-descriptions-item>
          <el-descriptions-item label="操作详情">{{ currentLogDetail.operationType }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentLogDetail.ipAddress }}</el-descriptions-item>
          <el-descriptions-item label="操作结果">{{ currentLogDetail.details }}</el-descriptions-item>
        </el-descriptions>

        <div class="detail-section">
          <h4>操作内容</h4>
          <p>{{ currentLogDetail.description }}</p>
        </div>

        <div v-if="currentLogDetail.details" class="detail-section">
          <h4>详细信息</h4>
          <pre>{{ currentLogDetail.details }}</pre>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getAdminLogsList, getAdminLogsByAdminId, getAdminLogsByModule, getAdminLogsByResult } from '@/api/adminLogs'
import { getAdminUserDetail } from '@/api/adminUser'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const logDetailDialogVisible = ref(false)
const currentLogDetail = ref(null)

const logFilterForm = reactive({
  adminId: '',
  operator: '',
  module: '',
  actionResult: '',
  dateRange: []
})

const logData = ref([])
const adminCache = ref({}) // 缓存管理员信息

const getModuleType = (module) => {
  const moduleMap = {
    '留学生审核': 'warning',
    '企业认证审核': 'success',
    '需求审核': 'primary',
    '请求管理': 'danger',
    '管理员管理': 'info',
    '角色管理': 'info'
  }
  return moduleMap[module] || 'info'
}

const getModuleText = (module) => {
  // 直接返回模块名称，因为后端返回的就是中文
  return module || '未知'
}

const getOperationTypeTag = (type) => {
  const typeMap = {
    login: 'success',
    logout: 'info',
    approve: 'success',
    reject: 'danger',
    create: 'primary',
    update: 'warning',
    delete: 'danger'
  }
  return typeMap[type] || 'info'
}

const getOperationTypeText = (type) => {
  const typeMap = {
    login: '登录',
    logout: '登出',
    approve: '通过',
    reject: '驳回',
    create: '创建',
    update: '更新',
    delete: '删除'
  }
  return typeMap[type] || '未知'
}

const handleLogFilter = () => {
  loadLogsList()
}

const handleLogReset = () => {
  logFilterForm.adminId = ''
  logFilterForm.operator = ''
  logFilterForm.module = ''
  logFilterForm.actionResult = ''
  logFilterForm.dateRange = []
  loadLogsList()
}

const handleViewLogDetail = (row) => {
  currentLogDetail.value = row
  logDetailDialogVisible.value = true
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadLogsList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadLogsList()
}

// 获取管理员信息
const getAdminInfo = async (adminId) => {
  if (adminCache.value[adminId]) {
    return adminCache.value[adminId]
  }
  
  try {
    const res = await getAdminUserDetail(adminId)
    if (res && res.code === 200 && res.data) {
      const adminInfo = {
        username: res.data.username,
        fullName: res.data.full_name || ''
      }
      adminCache.value[adminId] = adminInfo
      return adminInfo
    }
  } catch (e) {
    // 获取管理员信息失败
  }
  
  return { username: `admin${adminId}`, fullName: '' }
}

// 时间范围筛选函数
const filterByDateRange = (data, dateRange) => {
  if (!dateRange || !Array.isArray(dateRange) || dateRange.length !== 2) {
    return data
  }
  
  const [startDate, endDate] = dateRange
  if (!startDate || !endDate) {
    return data
  }
  
  const startTime = new Date(startDate).getTime()
  const endTime = new Date(endDate).getTime() + 24 * 60 * 60 * 1000 - 1 // 包含结束日期当天
  
  return data.filter(item => {
    const itemTime = new Date(item.operationTime).getTime()
    return itemTime >= startTime && itemTime <= endTime
  })
}

// 加载日志列表
const loadLogsList = async () => {
  loading.value = true
  try {
    // 构建请求参数，过滤掉不需要的参数
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    // 只添加有值的筛选条件
    if (logFilterForm.adminId) {
      params.adminId = logFilterForm.adminId
    }
    if (logFilterForm.operator) {
      params.operator = logFilterForm.operator
    }
    if (logFilterForm.module) {
      params.module = logFilterForm.module
    }
    if (logFilterForm.actionResult) {
      params.actionResult = logFilterForm.actionResult
    }
    // 注意：dateRange 不发送到后端，只在前端筛选
    
    let res
    if (logFilterForm.adminId) {
      // 如果指定了管理员ID，使用专门的接口
      res = await getAdminLogsByAdminId(logFilterForm.adminId, params)
    } else if (logFilterForm.module) {
      // 如果指定了模块，使用模块查询接口
      res = await getAdminLogsByModule(logFilterForm.module, params)
    } else if (logFilterForm.actionResult) {
      // 如果指定了操作结果，使用结果查询接口
      res = await getAdminLogsByResult(logFilterForm.actionResult, params)
    } else {
      // 否则使用通用列表接口
      res = await getAdminLogsList(params)
    }
    
    if (res && res.data) {
      // 先创建基础数据
      let baseData = res.data.map(item => ({
        id: item.logId,
        adminId: item.adminId,
        operationTime: item.actionTime,
        module: item.module,
        operationType: item.actionDetails,
        ipAddress: item.ipAddress,
        description: item.actionDetails,
        userAgent: '',
        details: `操作结果: ${item.actionResult}, 目标ID: ${item.targetId}`,
        operator: `管理员${item.adminId}` // 临时显示
      }))
      
      // 应用时间范围筛选
      baseData = filterByDateRange(baseData, logFilterForm.dateRange)
      
      // 获取所有不重复的管理员ID
      const adminIds = [...new Set(baseData.map(item => item.adminId))]
      
      // 批量获取管理员信息
      const adminPromises = adminIds.map(adminId => getAdminInfo(adminId))
      const adminResults = await Promise.all(adminPromises)
      
      // 创建管理员信息映射
      const adminMap = {}
      adminIds.forEach((adminId, index) => {
        adminMap[adminId] = adminResults[index]
      })
      
      // 更新操作人显示
      logData.value = baseData.map(item => ({
        ...item,
        operator: adminMap[item.adminId]?.fullName || adminMap[item.adminId]?.username || `管理员${item.adminId}`
      }))
      
      // 更新总数（筛选后的数量）
      total.value = baseData.length
    }
  } catch (e) {
    // 错误处理
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadLogsList()
})
</script>

<style scoped>
.admin-logs {
  padding: 0;
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
}

.tab-content {
  padding: 20px 0;
}

.table-card {
  margin-bottom: 20px;
  width: 100%;
}

.filter-card {
  margin-bottom: 20px;
  width: 100%;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #333;
}

.detail-section p {
  color: #666;
  line-height: 1.6;
}

.detail-section pre {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  color: #666;
  font-size: 12px;
  overflow-x: auto;
}
</style> 